<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>vue发送websocket-to springboot</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

</head>
<body>

<div id="app">
    <input type="text" v-model="book.title" placeholder="书名">
    <input type="text" v-model="book.author" placeholder="作者">
    <input type="text" v-model="book.price" placeholder="价格">
    <input type="text" v-model="book.category" placeholder="类别">
    <button @click="addBook">运行 WebSocket</button>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                book: {
                    title: '',
                    author: '',
                    price: '',
                    category: ''
                },
                websocketPath: 'ws://localhost:8090/websocket',
                ws: null
            }
        },
        mounted() {
            this.ws = new WebSocket(this.websocketPath);
            this.ws.onopen = this.open;
            this.ws.onerror = this.error;
            this.ws.onmessage = this.getMessage;
            this.ws.onclose = this.close;
        },
        methods: {
            open: function () {
                this.ws.send("发送数据");
                console.log("websocket连接成功...");
            },
            error: function () {
                console.log("连接错误")
            },
            getMessage: function (event) {
                let received_msg = event.data;
                this.$message({
                    message: received_msg,
                    type: 'success'
                });
            },
            close: function () {
                console.log("websocket连接已经关闭")
            },
            addBook: function () {
                let _this = this;
                axios.put('/api/admin/addBook', this.book)
                    .then(function (response) {
                        console.log(response);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        },
        destroyed() {
            this.ws.onclose = this.close();
        }
    });
</script>

</body>
</html>